package com.woniuxy.confirm;

import com.rabbitmq.client.*;
import com.woniuxy.utils.RabbitConnection;
import lombok.extern.log4j.Log4j2;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeoutException;

/**
 * @Author: linKe
 * @Date: 2022/1/10 15:49
 * @FileName: Producer
 * @version: 1.0
 * @Description: Confirm -- 生产者确认
 * 发送端的消息确认
 * Confirm 管理有没有进交换机
 */
@Log4j2
public class ProducerConfirm {

    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        Connection connection = RabbitConnection.getConnection();
        // 连接通道
        Channel channel = connection.createChannel();
        // 开启confirm监听
        channel.confirmSelect();
        // 添加confirm监听回调
        channel.addConfirmListener(new ConfirmListener() {
            @Override
            public void handleAck(long deliveryTag, boolean multiple) throws IOException {
                log.info("ACK");
                // 信封的标记
                log.info("deliveryTag:" + deliveryTag);
                // 是否同时确认多条
                log.info("multiple:" + multiple);
            }

            @Override
            public void handleNack(long deliveryTag, boolean multiple) throws IOException {
                log.info("NACK");
            }
        });
        // 监听是否投递到队列    路由错误的返回提示 生产者确认
        channel.addReturnListener(new ReturnListener() {
            @Override
            public void handleReturn(int replyCode, String replyText, String exchange, String routingKey, AMQP.BasicProperties properties, byte[] body) throws IOException {
                log.info("replyCode:" + replyCode);
                log.info("replyText:" + replyText);
                log.info("exchange:" + exchange);
                log.info("routingKey:" + routingKey);
                log.info("properties:" + properties);
                log.info("body:" + new String(body));
            }
        });
        for (int i = 0; i < 9; i++) {
            Thread.sleep(1000);
            /*
            (String exchange, String routingKey, boolean mandatory, BasicProperties props, byte[] body)
            发布消息。 如果资源驱动的警报 生效， Channel#basicPublish调用最终将被阻塞。
            参数：
                exchange 交换 - 将消息发布到的交换
                routingKey – 路由键        email1111 不存在的路由
                mandatory 强制 - 如果要设置“强制”标志，则为 true    开启return的监听
                props - 消息的其他属性 - 路由标头等
                body 正文 - 消息正文
             */
            channel.basicPublish("exchangeTopic", "email1111", true, null, ("邮箱服务..." + i).getBytes(StandardCharsets.UTF_8));
            /// channel.basicPublish("", "queueEmailWork", null, ("短信服务..."+i).getBytes(StandardCharsets.UTF_8));
            log.info("发送成功");
        }
        // 关闭资源 使用生产者确认连接不能关
        //RabbitConnection.close(connection,channel);
    }
}
